package com.Blog.www.filter;

import com.Blog.www.constant.SqlConstant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author 君未洋
 */
@WebFilter(value = "/*"/*, dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD}*/)
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转换方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String contextPath = request.getContextPath();
        //获取资源请求路径
        String uri = request.getRequestURI();
        Boolean flag = true;
        if (uri.contains("/login.jsp") || uri.contains("index.jsp")) {
            //在所有的登录相关界面查询cookie
            //如果有登录相关信息
            Cookie[] cs = request.getCookies();
            //获取数据,并遍历
            if (cs != null) {
                for (Cookie c : cs) {
                    if (SqlConstant.AUTO_LOGIN.equals(c.getName())) {
                        System.out.println("过滤器查询到的数据为" + c.getValue());
                        flag = false;
                        request.getSession().removeAttribute(SqlConstant.AUTO_LOGIN);
                        request.getSession().setAttribute(SqlConstant.AUTO_LOGIN, Integer.parseInt(c.getValue()));
                        //有就调用数据查询下这个id的用户,然后直接跳转回主页面
                        request.getRequestDispatcher("/User/autoLogin").forward(servletRequest, servletResponse);
                        return;
                    }
                }
            }
        }
        if (flag) {
            //其他状态直接放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
